package com.jf.cloud.service.sysmanager.support;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UrlPathHelper;

import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.HttpServletUtil;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.entity.SysStaff;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 用户session是否过期
 */
@Configuration
public class SessionInterceptor extends BaseController implements HandlerInterceptor {
    /**
     * 保存登录过的用户信息
     */
    public static Map<String, TokenUserInfo> UserSessionMap = new ConcurrentHashMap<String, TokenUserInfo>();
    
    @Autowired
	private TokenHandler tokenHandler;
    
    /**
     * 用户超时时间 30分钟-------->2周
     */
    public static long UserTimeOut = 14 * 24 * 60 * 60 * 1000;

    /**
     * 【代练宝】保存登录过的用户信息
     */
//	public Map<String, TokenUserInfo> DlbUserTokenMap = new ConcurrentHashMap<String, TokenUserInfo>();
    public SessionInterceptor() {

    }

    static Log log = LogFactory.getLog(SessionInterceptor.class);

    // 不需要过滤的模块
    private static Map<String, String> notFilterURL = new HashMap<String, String>();

    static {
    	notFilterURL.put("/login", "后台登陆");
    	
    	notFilterURL.put("/baseType/bigSelect", "基础类型 大类");
    	notFilterURL.put("/baseType/select", "基础类型");
    	notFilterURL.put("/basePropsConfig/refreshConfig", "刷新基础属性配置");
    	
    	notFilterURL.put("/appLogin/smsLogin", "短信验证码登录");
    	notFilterURL.put("/appLogin/thirdLogin", "第三方登录");
    	notFilterURL.put("/appLogin/getWxSmallCodeOpenId", "获取微信小程序的openId");
        notFilterURL.put("/appLogin/getWxSmalldDcryptPhone", "获取微信小程序手机号");
    	
    	notFilterURL.put("/sms/sendCaptchaSms", "发送短信验证码");
    	notFilterURL.put("/sms/checkSMS", "校验短信验证码");
    	notFilterURL.put("/appTeam/myTeam", "战队");
    	notFilterURL.put("/appTeam/pubgTeamDetail", "战队详情");
    	
    	notFilterURL.put("/appVersion/checkUpgrade", "APP 是否更新");

    	//点卡
    	notFilterURL.put("/cardUser/add", "点卡 添加用户");
    	notFilterURL.put("/cardUser/update", "点卡 更新用户");
    	notFilterURL.put("/cardUser/data", "点卡 查询用户");
    	notFilterURL.put("/cardUser/getUserDetail", "点卡 查询用户");
    	notFilterURL.put("/cardUser/getGoogleCode", "点卡 获取用户验证码");
    	notFilterURL.put("/cardUser/allocation", "点卡 分配");
    	notFilterURL.put("/cardUser/residue/allocation", "点卡 剩余分配");
    	notFilterURL.put("/cardOptRecord/data", "点卡 客服查询");
    	notFilterURL.put("/cardOptRecord/submit", "点卡 客服提交结果");
    	notFilterURL.put("/cardBatch/list", "点卡 项目统计");
    	notFilterURL.put("/cardUser/saveUserInfo", "布谷官网 用户填写联系信息");

    }

    // 不需验证登录的模块
    private static Map<String, String> notVerifyTokenURL = new HashMap<String, String>();

    static {
        // 代练APP 不需要验证登录的 地址
    	notVerifyTokenURL.put("/index", "代练宝APP 登录");
    }

    /**
     * 在业务处理器处理请求之前被调用  用户session是否过期
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        String url = urlPathHelper.getLookupPathForRequest(request);
		if(notFilterURL.containsKey(url)){
			return true;
		}
		
		String token = getParamValueString(request, "token");
		String userId = tokenHandler.getCommUserInfoByToken(token);
		if (url.indexOf("/app") == 0) {
			if (userId == null || userId.trim().length() == 0) {
				HttpServletUtil.write(response, "{\"code\":-2, \"message\":\"请重新登陆\"}");
				return false;
			} else {
				return true;
			}
		}
        
        if(StringUtils.isNotBlank(url)  && url.length() >= 1){
        	url = url.substring(1, url.length());
        }
		
        SysStaff sysStaff = getLoginUser(request);
		if(StringUtils.isNotBlank(url) && sysStaff == null){
			request.getRequestDispatcher("/").forward(request, response);
		}
		return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }


    /**
     * WebApp【Andriod】客户端令牌是否没有过期【并且移除已经过期的用户】
     *
     * @param token 客户端令牌
     * @return
     * @author 罗伟 创建时间：2014-12-11 16:15:36
     */
    public static boolean userIsTimeOutWeb(String token) {
        boolean flag = true;
        if (UserSessionMap.containsKey(token)) {
            TokenUserInfo tokenUserInfo = UserSessionMap.get(token);
            Long value = tokenUserInfo.getSessionTime();
            if ((System.currentTimeMillis() - value) > 0) {
                flag = false;
                UserSessionMap.remove(token); //移除过期用户
            } else {
                tokenUserInfo.setSessionTime(System.currentTimeMillis() + UserTimeOut);
            }
            log.info("★★★★★★Web访问★★★★★【" + DateUtil.getCurrentDateTime() + "】有【" + UserSessionMap.size() + "】用户在线★★★★★★★★★★★");
        } else {
            flag = false;
        }
        return flag;
    }

    /**
     * 根据token查找用户id
     */
    public static String tokenToUserId(Map<String, TokenUserInfo> userMap, String token) {
        try {
            if (userMap == null || !StringUtil.notNull(token) || !userMap.containsKey(token)) {
                return "";
            }
            TokenUserInfo tokenUserInfo = userMap.get(token);
            if (null == tokenUserInfo) {
                log.info("=============根据token查找用户id开始================");
                log.info("=============userMap================" + JsonUtil.toJSON(userMap));
                log.info("=============token================" + token);
                return "";
            }
            return tokenUserInfo.getUserId();
        } catch (Exception e) {
            log.error("根据token查找用户id报错", e);
            return "";
        }
    }

}
